import { asyncRoutes, constantRoutes } from "@/router";
const routerName = [
  "platform.employee.list",
  "illness.info.list",
  "iTlness.info.audit",
  " inspectionInfo.info.list",
  "inspectionInfo.info.publish",
  "maintenance.info.list",
  "maintenance.info .publish",
  "permisstion.info.list",
  "data.statistics .info",
  "tree.info.list",
  "tree.kind.list",
];

function hasPermission(roles, route) {
  console.log(roles, route, "roles, route");
  if (route.meta && route.meta.name) {
    console.log(roles.includes(route.meta.name));
    return roles.includes(route.meta.name);
    // return false
  } else {
    return true;
  }
}
// 过滤动态路由
export function filterAsyncRoutes(routes, roles) {
  const res = [];
  console.log(routes, roles);
  routes.forEach((route) => {
    const tmp = { ...route };
    console.log(tmp, "tmp");
    console.log(hasPermission(roles, tmp), "hasPermission(roles, tmp)");
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });
  console.log(res);
  return res;
}
const state = {
  routes: [],
  addRoutes: [],
};
const mutations = {
  SET_ROUTES: (state, routes) => {
    console.log("SET_ROUTES", routes);
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
    console.log("000000000000000000000000", state.routes);
  },
};
const actions = {
  generateRoutes({ commit }, roles) {
    console.log(roles);
    return new Promise((resolve) => {
      let accessedRoutes;
      if (roles.includes("*")) {
        accessedRoutes = asyncRoutes || [];
      } else {
        console.log(asyncRoutes, "asyncRoutes");
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
      }
      let arr = [];
      accessedRoutes.forEach((element) => {
        if (element.children && element.children.length) {
          arr.push(element);
        }
      });
      console.log(accessedRoutes);
      commit("SET_ROUTES", arr);
      resolve(arr);
      // resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
